package com.relytosoft.mizar.media.host.emqx;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.relytosoft.mizar.media.common.constant.MediaMqConstants;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * @author lj
 * @date 2022/6/15 14:24
 */
@Component
public class BehaviorDataMqttMessageListener implements com.relytosoft.mizar.media.common.emqx.listener.BehaviorDataMqttMessageListener {

    public static final Logger log = LoggerFactory.getLogger(BehaviorDataMqttMessageListener.class);

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        try {
            boolean isConsume = false;
            String mqttMsg = new String(message.getPayload(), StandardCharsets.UTF_8);
            JSONObject jsonObject = JSON.parseObject(mqttMsg);
            String opType = jsonObject.getString("OpType");
            String data = jsonObject.getString("Data");
            //判断topic是否为行为分析任务
            if (topic.equals(MediaMqConstants.BEHAVIOR_DATA_TOPIC)) {
                switch (opType) {
                    //添加行为分析任务
                    case "UPDATE_BEHAVIOR_TASK_ID":
                        isConsume = updateBehaviorTaskId(data);
                        break;
                    default:
                        break;
                }
            }

            log.info("线程名称：【" + Thread.currentThread().getName() + "】" + "接收的主题：" + topic + ",接收的操作类型：" + opType + "，执行结果：" + isConsume);
        } catch (Exception e) {
            log.info("线程名称：【" + Thread.currentThread().getName() + "】" + "接收的主题：" + topic + ",处理发生错误：" + e.getMessage());
        }
    }

    private boolean updateBehaviorTaskId(String data) {
        //TODO 更新redis和数据库中的数据
        return true;
    }
}

